package com.foxchen.fanjingmontainticket.schedule;

import com.foxchen.fanjingmontainticket.schedule.task.BuyTicketTask;
import jakarta.annotation.PreDestroy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Component
public class DynamicTaskService {
    private static final Map<String, ScheduledFuture<?>> TASK_MAP = new ConcurrentHashMap<>();
    private static final ThreadPoolTaskScheduler THREAD_POOL_TASK_SCHEDULER;
    static {
        THREAD_POOL_TASK_SCHEDULER = new ThreadPoolTaskScheduler();
        THREAD_POOL_TASK_SCHEDULER.setPoolSize(100);
        THREAD_POOL_TASK_SCHEDULER.setThreadNamePrefix("DynamicTaskService-");
        THREAD_POOL_TASK_SCHEDULER.initialize();
    }

    @PreDestroy
    public void destroy() {
        THREAD_POOL_TASK_SCHEDULER.shutdown();
    }


    // 添加任务：周期（秒）执行
    public void addTask(BuyTicketTask task, Instant instant) {
        ScheduledFuture<?> future = THREAD_POOL_TASK_SCHEDULER.schedule(task, instant);
        TASK_MAP.put(task.getTicketRecord().getTaskUuid(), future);
    }

    // 移除任务
    public boolean removeTask(String taskId) {
        ScheduledFuture<?> future = TASK_MAP.remove(taskId);
        if (future != null) {
            return future.cancel(false);
        }
        return false;
    }
}
